import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;


public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int i = 1;
		// DATA
		byte[] dataBytes = new byte[1024];
		ByteBuffer.wrap(dataBytes).order(ByteOrder.LITTLE_ENDIAN).putInt(0).array();
			try {		
				for(int j=0;j<=32770;j++){
					Socket s = new Socket("54.201.184.170", 1234);
					InputStream in = s.getInputStream();
					OutputStream out = s.getOutputStream();
					
					// Command
					byte[] commandBytes = new byte[33];
					ByteBuffer bb = ByteBuffer.wrap(commandBytes).order(ByteOrder.LITTLE_ENDIAN);
					bb.put((byte)0x01);
					System.out.println("Send: "+i);
					// Key
					double key = Math.random();
					bb.putDouble(key);
					System.out.println("Send key: "+key);
					
					// Send
					out.write(commandBytes);
					out.write(dataBytes);

					byte[] inputBytes = new byte[1025];
			    	int totalBytesRcvd2 = 0;
			    	// Read until the expected length of data
			    	while (totalBytesRcvd2 < inputBytes.length) {
			    		int bytesRcvd;
			    		if ((bytesRcvd = in.read(inputBytes, totalBytesRcvd2,  
			    				inputBytes.length - totalBytesRcvd2)) == -1)
			                   	throw new SocketException("Connection close prematurely");
			    		 	totalBytesRcvd2 += bytesRcvd;
			    	}
					
					in.read(inputBytes);
					ByteBuffer bb2 = ByteBuffer.wrap(inputBytes).order(ByteOrder.LITTLE_ENDIAN);
					System.out.println(" Error code : " + bb2.get());
					in.close();
					out.close();
					s.close();

				}

			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

}
